<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS打字小游戏</title>
    <style>
        body {
            padding: 0px;
            margin: 0;
        }
        .info        { width:500px; margin:0 auto; }
        .info li{ float:left; height:30px; margin-right:2em; line-height:30px; list-style: none}

        #gameStage {
            width: 90%;
            height: 400px;
            background-color: aquamarine;
			margin:0px;
			padding:100px;
			border-bottom: 5px solid black;
        }
		#line{
		position:relative;
		margin-top:500px;
		margin-left:0px;
		/*margin:500px auto;*/
		width: 100%;
        height: 1px;
		background: #000;
		padding:1px;
		}
		#foot{
		margin:0px auto; width:100%; height:80px; background:#9f9;}
        #gameover{
              /*margin-top:100px;*/

              margin-left: 300px;
              text-align: center;
              font-size: 100px;
              width: 500px;
              height: 200px;
              color: black;
              background: red;
              position: absolute;
          }
        #score{
            /*margin-top:100px;*/
            margin: 0px;
            text-align: center;
            font-size: 50px;
            width: 500px;
            height: 100px;
            color: black;
            background: red;
            position: relative;
        }
        #ss{
            margin: 1px 100px 0px 0px;
            text-align: center;
            font-size: 60px;
            width:100%;
            height:80px;
            color: red;
            background: #9f9;
            position: absolute;
        }
    </style>
    
</head>
<body>
<ul class="info">
    <li>选择速度:
        <select id="setSpeed">
        <option value="400">慢(400)</option>
        <option value="200">中(200)</option>
        <option value="100">快(100)</option>
        </select>
    </li>
    <li>按“空格键” 开始/暂停</li>
</ul>

<div id="gameStage">

</div>
<div id="foot"></div>

<script>
  /**
   * 字母
   * @param id
   * @param alphabet
   * @param posX
   * @param posY
   * @param size
   * @constructor
   */

  function Word(id, alphabet, posX, posY, size) {

    //初始化数据
    this.id = id || '';
    this.alphabet = alphabet || 'a';
    this.posX = posX || 0;
    this.posY = posY || 0;
    this.size = size || 64;
    this.score = 0;


    // 新建
    this.create = function () {
      var str = '<span class="word" id="alphabet-' + this.id + '">' + this.alphabet + '</span>';
	  
      var gameStage = document.getElementById('gameStage');
      gameStage.innerHTML += str;

      var divNode = document.getElementById('alphabet-' + this.id);
      divNode.style.position = 'absolute';
      divNode.style.fontSize = this.size + 'px';
      divNode.style.left = this.posX + 'px';
      divNode.style.top = this.posY + 'px';

    };

    // 重置.
    this.reset = function () {
      var divNode = document.getElementById('alphabet-' + this.id);
      divNode.style.display = 'none';
      this.moveTo(0, 0);
    };

    // 移动到指定点
    this.moveTo = function (posX, posY) {
      this.posX = posX;
      this.posY = posY;

      var divNode = document.getElementById('alphabet-' + this.id);
      divNode.style.left = posX + 'px';
      divNode.style.top = posY + 'px';
    };

  }

  /**
   * 导演类
   */

  var director = {
    alphabets: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],

    nodes: new Array(),
      pause:1,
      end:0,
      flag:0,
      speed:400,
    /**
     * 逐帧运行
     */
    runFrame: function () {

      //更新已经产生所有点的坐标
      for (var index in this.nodes) {
        var node = this.nodes[index];
        if (node) {
          node.moveTo(node.posX, node.posY + 5);
          if(node.posY==545){
              var str2='<div id="gameover">' + "GameOver"+ '<p id="score">当前分数：'+this.score+'</p>'+'</div>';
              var foot1=document.getElementById('gameStage');
              foot1.innerHTML+=str2;
                this.flag=1;
                var change=document.getElementById("gameStage");
                change.style.borderBottom='5px solid red';
                return this.flag;
          }
        }
      }

      //随机产生字母
      var r = Math.floor(Math.random() * this.alphabets.length);
      var w = new Word(new Date().getTime(), this.alphabets[r]);

      w.create();
      this.nodes.push(w);

      var posX = Math.floor(Math.random() * window.innerWidth);
      if (posX < 50) {
        posX = 100;
      }
      if (posX >= window.innerWidth - 100) {
        posX = window.innerWidth - 100;
      }

      w.moveTo(posX, 0);
    },

    /**
     * 开始游戏
     */
    start: function () {

        var _this = this;
        arguments[0] ? _this.speed=arguments[0] : false;//选择速度
        //监听键盘事件
        document.onkeydown = function () {
            var code = event.keyCode;
            if (code == 32 ) {
                _this.pause *= -1;
                (_this.pause==-1) ? _this.end=window.setInterval(function () {
                        var f=_this.runFrame();
                        if(f==1){
                            clearInterval(_this.end);
                        }
                    },_this.speed): window.clearInterval(_this.end);
            }
            else {
                var alphabet = String.fromCharCode(event.keyCode); //获取键盘敲中的字母
                for (var i = 0, len = _this.nodes.length; i < len; i++) {
                    if (!_this.nodes[i]) {
                        continue;
                    }
                    if (alphabet === _this.nodes[i].alphabet) {
                        _this.nodes[i].reset();
                        scoreCounter.incScore();
                        _this.score = scoreCounter.getScore();
                        var str1 = '<div id="ss">分数:' + _this.score + '</div>';
                        var foot = document.getElementById('foot');
                        foot.innerHTML += str1;
                        _this.nodes[i] = null;

                    }

                }


            }

        },
        /*	for (var k = 0, len = _this.nodes.length; k < len; k++) {
		  var died= 400;
		  if(died ==_this.nodes[k].posY)
		  {
		  		var str2='<span class="" >' +"jieshu"+ _this.nodes[k].posY + '</span>';
				var foot1=document.getElementById('foot');
				foot1.innerHTML+=str2;
		  }
		 }*/


      //游戏主循环
    //    if(pause==-1)
     //   {
            clearInterval();
        /* var tout= setInterval(
             function () {
            var flag=_this.runFrame();
            if(flag==1){
                clearInterval(tout);

              }
          }, 100);*/
      //  }
    }
  }

  /**
   * 计分器
   */
  var scoreCounter = {
    score: 0,
    incScore: function () {
      this.score++;
    },
    getScore: function () {
      return this.score;
    }
  };

window.onload=function () {
    document.getElementById("setSpeed").onchange = function(){ this.blur(); director.start(this.value); };
    director.start();
}


</script>
</body>
</html>